package com.heima.search.service;

import com.heima.model.search.dtos.UserSearchDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    //    reids的key的前缀
    private String PRE_FIX = "ld:search:word:";
    /**
     * 保存用户搜索记录
     * @param dto
     * @param userId
     */
    @Async  //使用异步方式保存
    public void saveUserWord(UserSearchDto dto, Integer userId){
        log.info("=====线程id={}"+Thread.currentThread().getId());
//        获取redis的key
        String key = getKey(dto, userId);

//        保存搜索记录的时间
//        redisTemplate.opsForZSet().add(key,dto.getSearchWords(),System.currentTimeMillis());
//        搜索次数
        redisTemplate.opsForZSet().incrementScore(key,dto.getSearchWords(),1);
//        设置 有效期为7天
        redisTemplate.expire(key,7, TimeUnit.DAYS);
    }

    /**
     * 获取 用户的搜索关键词
     * @return
     */
    public Set<String> getSearchWord(UserSearchDto dto, Integer userId){
        String key = getKey(dto, userId);

//        根据搜索时间，倒叙获取数据
        Set<String> set = redisTemplate.opsForZSet().reverseRange(key, 0, -1);
        return set;
    }

    /**
     * 删除搜索记录
     * @param dto
     * @param userId
     */
    public void delSearchWord(UserSearchDto dto,Integer userId){
        String key = getKey(dto, userId);
        redisTemplate.opsForZSet().remove(key,dto.getSearchWords());
    }

    public String getKey(UserSearchDto dto,Integer userId){

        String key= PRE_FIX;
        if(userId != null && userId!=0){
            key += userId;
        }else {
            key += dto.getEquipmentId();
        }
        return  key;

    }

}
